<template>
    <view>
        <!-- pages/setParking2/index.wxml -->
        <view class="body">
            <van-cell-group>
                <van-cell title="停车场" :value="parkingName" />
                <view class="xgcw">
                    <view v-if="id" class="cw1">
                        <view style="flex: 4">
                            <van-cell title="车位号" :value="parkingNumber" @click="showPopupcw" />
                        </view>
                        <!-- <view class="xg1" bindtap="changeparkingNumber">修改</view> -->
                    </view>
                    <view v-else class="cw2">
                        <view style="flex: 4">
                            <van-cell title="车位号" is-link :value="parkingNumber" @click="showPopupcw" />
                        </view>
                        <!-- <view class="xg2" bindtap="changeparkingNumber">修改</view> -->
                    </view>
                </view>
                <van-cell title="起租时间" :value="date ? date : '请选择'" is-link @click="onDisplay" />
                <van-calendar :default-date="caleDate" v-model="showcalendar" @close="onClose" @confirm="onConfirm" />
                <van-cell title="租赁期限" :value="cycle ? cycle : '请选择'" is-link @click="showPopupcycle" />
                <van-cell title="共享时间段" value="全天（默认）" />
            </van-cell-group>
            <!-- <view class="gz">
        <view class="gz-r">平台统一定价：参照车场统一定价</view>
    </view> -->
            <view class="rules">
                <view class="rules-title">定价规则</view>
                <view class="rules-content">
                    <view>1、车场收费标准：包月费用为{{ price.unitPrice / 100 || '--' }}元/月。</view>
                    <view>2、车位主的收益为停车总费用*60%。</view>
                </view>
            </view>
            <!-- <view class="agree">
        <van-checkbox value="{{ checked }}" bind:change="onChangeCheckbox">
            我已经阅读并同意《停车服务协议》
        </van-checkbox>
    </view> -->
            <view class="rule">
                <van-checkbox v-model="checked" @change="onChangeCheckbox" checked-color="#00BCAB"></van-checkbox>
                <text @tap="showRule" style="padding-left: 10rpx">我已经阅读并同意《停车服务协议》</text>
            </view>
            <view class="agree-btn">
                <van-button type="info" @tap.native="goOk">确定发布</van-button>
            </view>
            <van-popup v-model="showcw" position="bottom" @close="onClosecw">
                <van-picker show-toolbar :columns="columnscw" @cancel="onCancelcw" @confirm="onConfirmcw" @change="onChangecw" />
            </van-popup>
            <!-- 车位修改弹窗 -->
            <!-- <van-dialog use-slot title="当前关联的车位：A73" show="{{ showcw }}" show-cancel-button confirm-button-open-type="getUserInfo" bind:close="onClose" bind:getuserinfo="getUserInfo">
        <van-cell-group>
            <van-field value="{{ value }}" placeholder="请输入用户名" border="{{ false }}" bind:change="onChange" />
        </van-cell-group>
        <view class="Tips">
            <view>温馨提示：</view>
            <view>提交修改后由物业审核，请耐心等待。详询物业中心。</view>
        </view>
    </van-dialog> -->
            <!-- 重复周期 -->
            <van-popup v-model="showcycle" close-icon="close" position="bottom" @close="onClosecycle">
                <van-picker show-toolbar title="选择周期" :columns="columns" @cancel="onCancel" @confirm="onConfirmcycle" />
            </van-popup>
        </view>
        <van-dialog id="van-dialog" confirm-button-text="我知道了" confirm-button-color="#00BCAB" />
        <van-dialog
            use-slot
            title="修改车位号"
            confirm-button-color="#00BCAB"
            v-model="showparkingNumber"
            show-cancel-button
            confirm-button-open-type="getUserInfo"
            @close="onCloseparkingNumber"
            @getuserinfo="getUserInfoparkingNumber"
        >
            <view style="padding-left: 30rpx">当前关联车号 {{ parkingNumber }}</view>
            <van-field v-model="parkingNumberValue" label="申请修改为" type="textarea" autosize :border="false" @change="changeValue" />
            <view class="Tips">温馨提示：提交修改后，由物业审核，请耐心等待。详询物业中心。</view>
        </van-dialog>
        <view class="rule-pop">
            <van-popup round v-model="showRulePop" @close="closeRule">
                <view class="rules">
                    <view class="rule-title">停车服务协议</view>
                    <!-- <view class="rule-content">
        {{platformRules}}
      </view> -->
                    <view class="rule-content"><rich-text :nodes="platformRules"></rich-text></view>
                    <view class="rule-line"></view>
                    <view class="rule-know" @tap="closeRule">我知道了</view>
                </view>
            </van-popup>
        </view>
    </view>
</template>

<script>
// pages/setParking2/index.js
// pages/setParking2/index.js
import util from './../../utils/util.js';
import api from './../../utils/api.js';
import { Dialog } from 'vant';
import config from './../../utils/config.js';
export default {
    data() {
        return {
            showcw: false,

            //车位
            date: '',

            //日期
            // unionId: " fb0feca5-0945-4989-b4aa-8c33413ff648",
            // unionId: wx.getStorageSync("unionId") || "",
            showcalendar: false,

            show: false,
            columnscw: [],

            //车位
            parkingNumber: null,

            parkingName: null,
            parkingCode: null,
            cycle: null,

            //周期
            showcycle: false,

            cycleindex: 0,

            columns: [
                {
                    text: '1个月',
                    index: 1
                },
                {
                    text: '2个月',
                    index: 2
                },
                {
                    text: '3个月',
                    index: 3
                },
                {
                    text: '4个月',
                    index: 4
                },
                {
                    text: '5个月',
                    index: 5
                },
                {
                    text: '6个月',
                    index: 6
                },
                {
                    text: '7个月',
                    index: 7
                },
                {
                    text: '8个月',
                    index: 8
                },
                {
                    text: '9个月',
                    index: 9
                },
                {
                    text: '10个月',
                    index: 10
                },
                {
                    text: '11个月',
                    index: 11
                },
                {
                    text: '12个月',
                    index: 12
                }
            ],

            checked: false,
            id: null,
            caleDate: [],
            showparkingNumber: false,
            parkingNumberValue: '',

            price: {
                unitPrice: 0
            },

            platformRules: config.platformRules,
            showRulePop: false,
            editData: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        if (options.id) {
            this.setData(
                {
                    id: options.id
                },
                () => {
                    this.getmySpaceList();
                }
            );
        } else {
            this.getmySpaceList();
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function() {}
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        onCloseparkingNumber() {
            this.setData({
                showparkingNumber: false
            });
        },

        getUserInfoparkingNumber() {
            this.setData({
                showparkingNumber: false
            });
            this.setspaceModify();
        },

        changeparkingNumber() {
            this.setData({
                showparkingNumber: true,
                parkingNumberValue: ''
            });
        },

        changeValue(e) {
            this.setData({
                parkingNumberValue: e.detail
            });
        },

        showPopupcw() {
            this.setData({
                showcw: true //车位
            });
        },

        //车位下拉选择
        onClosecw() {
            this.setData({
                showcw: false //车位
            });
        },

        onCancelcw() {
            this.setData({
                showcw: false //车位
            });
        },

        onConfirmcw(e) {
            this.setData({
                showcw: false
            });
        },

        onChangecw(e) {
            this.setData(
                {
                    parkingNumber: e.detail.value.parkingNumber,
                    parkingName: e.detail.value.parkingName,
                    parkingCode: e.detail.value.parkingCode
                },
                () => this.getProducts()
            );
        },

        //时间
        onDisplay() {
            this.setData({
                showcalendar: true
            });
        },

        onClose() {
            this.setData({
                showcalendar: false
            });
        },

        // formatDate(date) {
        //   date = new Date(date);
        //   return `${date.getMonth() + 1}/${date.getDate()}`;
        // },
        formatDate(date) {
            var Dates = new Date(date);
            var Y = Dates.getFullYear();
            var M = Dates.getMonth() + 1;
            var D = Dates.getDate();
            var times = Y + (M < 10 ? '/0' : '/') + M + (D < 10 ? '/0' : '/') + D; // return `${date.getFullYear() / date.getMonth() + 1}/${date.getDate()}`;

            return times;
            console.log(times);
        },

        onConfirm(event) {
            const start = event.detail;
            console.log(start);

            if (start && start.length != 0) {
                this.setData({
                    showcalendar: false,
                    date: `${this.formatDate(start)}`
                });
            } else {
                this.setData({
                    showcalendar: false
                });
            }
        },

        showPopuptime() {
            this.setData({
                show: true
            });
        },

        onClosetime() {
            this.setData({
                show: false
            });
        },

        // onInput(event) {
        //   this.setData({
        //     currentDate: event.detail
        //   });
        // },
        showPopupcycle() {
            this.setData({
                showcycle: true
            });
        },

        onClosecycle() {
            this.setData({
                showcycle: false
            });
        },

        onConfirmcycle(event) {
            const { picker, value, index } = event.detail;
            this.setData({
                showcycle: false,
                cycle: event.detail.value.text,
                cycleindex: event.detail.value.index
            }); // Toast(`当前值：${value}, 当前索引：${index}`);
        },

        onCancel() {
            this.setData({
                showcycle: false
            }); // Toast('取消');
        },

        onChangeCheckbox(event) {
            this.setData({
                checked: event.detail
            });
        },

        goOk() {
            this.setparkingRelease();
        },

        //修改车位
        setspaceModify() {
            const unionId = uni.getStorageSync('unionId') || '';
            util.request(
                api.spaceModify +
                    '?userUnionId=' +
                    unionId +
                    '&parkingCode=' +
                    this.parkingCode +
                    '&parkingNumber=' +
                    this.parkingNumberValue +
                    '&oldParkingNumber=' +
                    this.parkingNumber,
                'get'
            ).then((res) => {
                if (res.success == true) {
                    uni.showToast({
                        title: res.data,
                        icon: 'none'
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            });
        },

        //我的车位
        getmySpaceList() {
            const unionId = uni.getStorageSync('unionId') || '';
            util.request(api.mySpaceList + '?userUnionId=' + unionId, 'get').then((res) => {
                if (res.code == 0) {
                    var array = [];

                    if (res.data) {
                        res.data.map((e, index) => {
                            if (e.authStatus == 1) {
                                array.push(
                                    Object.assign({}, e, {
                                        text: e.parkingNumber
                                    })
                                );
                            }
                        });
                    }

                    this.setData(
                        {
                            columnscw: array,
                            //车位
                            parkingNumber: array.length && array[0].parkingNumber ? res.data[0].parkingNumber : '',
                            parkingName: array.length && array[0].parkingName ? res.data[0].parkingName : '',
                            parkingCode: array.length && array[0].parkingCode ? res.data[0].parkingCode : '',
                            editData: this.id && array.length ? array.find((e) => e.id == this.id).plmParkingSpaceManage : {}
                        }, //   editData: this.data.id
                        //     ? {
                        //         validStartTime: "2021-04-27 00:00:00",
                        //         validEndTime: "2021-06-28 00:00:00",
                        //         tempStartTime: "13:00:00",
                        //         tempEndTime: "12:00:12",
                        //         tempCycle: "1111111"
                        //       }
                        //     : {}
                        // },
                        () => this.reLoadData()
                    ); // console.log(res.data[0].parkingNumber, "aasa");

                    this.getProducts();
                }
            });
        },

        //发布车位
        setparkingRelease() {
            console.log('setparkingRelease');
            var validStartTime = this.date.replaceAll('/', '-');
            var enddatemonth = +this.date.split('/')[1] + +this.cycleindex;
            var enddateyear = +this.date.split('/')[0].toString();

            if (enddatemonth < 10) {
                enddatemonth = '0' + enddatemonth;
            } else if (enddatemonth > 12) {
                enddateyear = +this.date.split('/')[0].toString() + 1;
                enddatemonth = enddatemonth - 12;
            }

            const endDataTime = enddateyear + '-' + enddatemonth + '-' + +this.date.split('/')[2];
            const unionId = uni.getStorageSync('unionId') || '';
            const param = {
                userUnionId: unionId,
                spaceNo: this.parkingNumber,
                parkingCode: this.parkingCode,
                type: 2,
                //1临停预约，2包整月，3夜间包月
                validStartTime: validStartTime + ' ' + '00:00:00',
                validEndTime: endDataTime + ' ' + '00:00:00'
            };
            console.log(this.checked);

            if (!validStartTime) {
                uni.showToast({
                    title: '请输入日期',
                    icon: 'none'
                });
                return;
            } else if (!this.cycle) {
                uni.showToast({
                    title: '请输入租赁期限',
                    icon: 'none'
                });
                return;
            } else if (!this.checked) {
                Dialog.alert({
                    message: '请阅读并同意《停车服务协议》'
                }).then(() => {
                    // on close
                });
                return;
            }

            if (this.checked) {
                util.request(api.parkingRelease, param, 'POST').then((res) => {
                    if (res.code == 0) {
                        // wx.requestSubscribeMessage({
                        //   tmplIds: ['xqUUPkB_Vno5teHtRMj8LNY684WDRo9_CVMffA03Pvc'],
                        //   success(sus) {
                        //     wx.navigateTo({
                        //       url: "../setParkingsuccess/index"
                        //     });
                        //   },
                        //   fail(err) {
                        //     wx.navigateTo({
                        //       url: "../setParkingsuccess/index"
                        //     });
                        //   },
                        // })
                        this.getchangeSaleStatus(); //发布成功直接上架
                        // wx.navigateTo({
                        //   url: "../setParkingsuccess/index"
                        // });
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            }
        },

        //  回写数据
        reLoadData() {
            const { id, editData } = this; // let cyclelist = JSON.parse(JSON.stringify(this.data.cyclelist));

            if (id) {
                const { validStartTime, validEndTime, tempStartTime, tempEndTime, tempCycle } = editData; // 整理日期

                const date = validStartTime.split(' ')[0].replaceAll('-', '/');
                let startm = validStartTime.split(' ')[0].split('-')[1];
                let endm = validEndTime.split(' ')[0].split('-')[1];
                const cycleindex = endm - startm;
                const cycle = this.columns.find((e) => e.index == cycleindex).text;
                console.log(cycleindex);
                this.setData({
                    date,
                    caleDate: validStartTime.split(' ')[0],
                    cycleindex,
                    cycle
                });
            }
        },

        //根据停车场编码获取车场产品的价格、免费时长--用于定价规则
        getProducts() {
            let param = {
                parkingCode: this.parkingCode,
                type: 2
            };
            util.request(api.findProductList, param, 'GET').then((res) => {
                if (res.success) {
                    let list = res.data.productList;
                    list.map((item) => {
                        if (item.type == 1) {
                            this.setData({
                                price: item
                            });
                        }
                    });
                }
            });
        },

        //展示规则
        showRule() {
            this.setData({
                showRulePop: true
            });
        },

        /**
         * 关闭规则
         */
        closeRule() {
            this.setData({
                showRulePop: false,
                checked: true
            });
        },

        //上架接口
        getchangeSaleStatus() {
            const unionId = uni.getStorageSync('unionId') || '';
            const param = {
                userUnionId: unionId,
                spaceNo: this.parkingNumber,
                parkingCode: this.parkingCode,
                saleStatus: 1
            };
            util.request(api.changeSaleStatus, param, 'POST')
                .then((res) => {
                    if (res.code == 0) {
                        // wx.showToast({ title: res.data, icon: "none" });
                        uni.navigateTo({
                            url: '../setParkingsuccess/index'
                        });
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    uni.showToast({
                        title: '请求异常，请重试',
                        icon: 'none'
                    });
                });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
